<script setup>
import api from '../api/user_api.js'
import {ref, onMounted} from "vue";
import {ElMessageBox} from "element-plus";
import lodash from 'lodash'

//定义绑定的数据
//表格中的数据
const tableData = ref([]);
const total=ref(0);
//定义对话框的显示状态
const editWinVisible = ref(false);
const addWinVisible=ref(false);
//查询数据
const searchObj = ref({
  current: 1,
  limit: 10,
  id:'',
  username:'',
  password:'',
  email:'',
  phone:'',
  real_name:'',
  gender:'',
  avatar:'',
  role:'司机', // 只展示司机角色
  driver_license:'',
  driver_apply_status: '',
  register_time:'',
});


//要修改或者新增的数据
const obj = ref({});
const search = async () => {
  try {
    // 确保角色过滤条件始终存在
    if (!searchObj.value.role) {
      searchObj.value.role = '司机';
    }

    console.log('发送的查询参数:', searchObj.value);
    var result = await api.getUserPage(searchObj.value.current, searchObj.value.limit, searchObj.value);
    console.log('收到的响应数据:', result);
    tableData.value = result.records;
    total.value = result.total;
  } catch (error) {
    console.error('获取用户列表时出错:', error);
    tableData.value = [];
    total.value = 0;
  }
  //try代替了
  //var result = await api.getUserList(searchObj.value);
  //tableData.value = result;
  //total.value=result.count;
}


//页面加载后要挂载的数据
onMounted(async () => {
  await search();
});
// 路由激活时重新加载数据
// onActivated(async () => {
//   检查是否已有数据，如果没有则加载
  // if (tableData.value.length === 0) {
  //   await search();
  // }
// });

//上传成功
const handleUploadSuccess = (response,file) => {
  console.log("-----------------");
  console.log(response);
  console.log(file);
  obj.value.avatar=response.data;
}//分页查询用
const handleSizeChange=()=>{
  search();
}//分页查询用
const handleCurrentChange=()=>{
  search();
}
//定义方法
const handlerSearch = () => {
  searchObj.value.current = 1;
  search();
}
const handlerAdd=()=>{//添加
  obj.value={};
  addWinVisible.value=true;//打开对话框
}
//新增对话框的取消按钮点击事件
const addCancel=()=>{
  obj.value={};//清空数据
  addWinVisible.value=false;//关闭新增对话框
}
//编辑对话框的取消按钮点击事件
const editCancel = () => {
  obj.value = {};//清空数据
  editWinVisible.value = false;//关闭对话框
}
//编辑对话框的提交按钮点击事件
const editCommit = async () => {
  await api.updateUser(obj.value);//提交修改数据
  await search();//刷新表格
  editWinVisible.value = false;//关闭编辑对话框
}
//新增对话框的提交按钮点击事件
const addCommit=async()=>{
  await api.addUser(obj.value);//提交新增数据
  search();//刷新表格
  addWinVisible.value=false;//关闭新增对话框
}
const handleEdit = (index, row) => {
  obj.value=lodash.clone(row);
  editWinVisible.value = true;
  console.log(index, row)
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗?',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async() => {
        await api.deleteUser(row.id);
        //重新加载数据
        //设置从第一页开始查询
        searchObj.value.current = 1;
        await search();
      })
      .catch(() => {
      })
}
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return dateTimeStr.replace('T', ' ');
}
</script>

<template>
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
    <el-form-item label="用户名">
      <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable />
    </el-form-item>
    <el-form-item label="手机号">
      <el-input v-model="searchObj.phone" placeholder="请输入手机号" clearable />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handlerAdd">新增</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="用户id" ></el-table-column>
    <el-table-column prop="username" label="用户名"></el-table-column>
    <el-table-column prop="password" label="密码"></el-table-column>
    <el-table-column prop="email" label="邮箱"></el-table-column>
    <el-table-column prop="phone" label="手机号"></el-table-column>
    <el-table-column prop="real_name" label="真实姓名"></el-table-column>
    <el-table-column prop="gender" label="性别"></el-table-column>
    <el-table-column prop="avatar" label="头像">
      <template #default="scope">
          <el-image
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"      style="width: 40px; height: 40px; object-fit: cover;"
              fit="cover"
              alt="用户头像"
          /></template>
    </el-table-column>
    <el-table-column prop="role" label="角色"></el-table-column>
    <el-table-column prop="driver_license" label="驾驶证号"></el-table-column>
    <el-table-column prop="driver_apply_status" label="司机申请状态">
      <template #default="scope">
        <span v-if="scope.row.driver_apply_status === 0">无申请</span>
        <span v-else-if="scope.row.driver_apply_status === 1">申请待审批</span>
        <span v-else-if="scope.row.driver_apply_status === 2">审批通过</span>
        <span v-else>未知</span>
      </template>
    </el-table-column>
    <el-table-column prop="register_time" label="注册时间">
      <template #default="scope">
        <span>{{ formatDateTime(scope.row.register_time) }}</span>
      </template>
    </el-table-column>
    <el-table-column label="处理按钮">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10,20,30,50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />

  <!--编辑对话框-->
  <el-dialog v-model="editWinVisible" title="编辑" width="500">
    <el-form :model="obj">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="100">
        <el-input v-model="obj.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="100">
        <el-input v-model="obj.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img  v-if="obj.avatar" :src="obj.avatar"  style="width:100px" />
          <img  v-else src='@/assets/upload.png'  style="width:100px"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="真实姓名" :label-width="100">
        <el-input v-model="obj.real_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" :label-width="100">
        <el-select v-model="obj.gender" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="驾驶证号" :label-width="100">
        <el-input v-model="obj.driver_license" autocomplete="off" />
      </el-form-item>
      <el-form-item label="司机申请状态" :label-width="100">
        <el-select v-model="obj.driver_apply_status" placeholder="请选择司机申请状态">
          <el-option label="无申请" value="0"></el-option>
          <el-option label="申请待审批" value="1"></el-option>
          <el-option label="审批通过" value="2"></el-option>
          <el-option label="申请被拒绝" value="3"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  <!--  新增对话框-->
  </el-dialog>
  <el-dialog v-model="addWinVisible" title="新增" width="500">
    <el-form :model="obj">
      <el-form-item label="用户名" :label-width="100">
        <el-input v-model="obj.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" :label-width="100">
        <el-input v-model="obj.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="100">
        <el-input v-model="obj.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="100">
        <el-input v-model="obj.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="头像" :label-width="100">
        <el-upload
            class="avatar-uploader"
            action="/api/upload/file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
        >
          <img  v-if="obj.avatar" :src="obj.avatar"  style="width:100px" />
          <img  v-else src='@/assets/upload.png'  style="width:100px"/>
        </el-upload>
      </el-form-item>
      <el-form-item label="真实姓名" :label-width="100">
        <el-input v-model="obj.real_name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" :label-width="100">
        <el-select v-model="obj.gender" placeholder="请选择性别">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="驾驶证号" :label-width="100">
        <el-input v-model="obj.driver_license" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style scoped></style>